const http = require('http');
const fs = require('fs');

let user = {
    name: '石兴龙',
    balance: '100.00'
}

let data = {
    success: true,
    msg: '',
    data: null
}

const decodeParam = function(param) {
    let d = {}
    var a = param.split('&')
    for (let item of a) {
        item = item.split('=')
        d[item[0]] = item[1]
    }
    return d;
}

const server = http.createServer((request, response) => {
    // 静态资源处理
    if (/.html$/.test(request.url)) {
        let filePath = __dirname + '/' + request.url
        response.writeHead(200);
        fs.createReadStream(filePath).pipe(response)
    } else {
        if (request.url.startsWith('/upload')) {
            let s = []
            request.on('data', function(data) {
                s.push(data)
            })
            request.on('end', function() {
                console.log(
                    s.toString()
                )
            })
        } else if (request.url.startsWith('/login')) {
            if (request.method === 'POST') {
                let s = []
                request.on('data', function(data) {
                    s.push(data);
                })
                request.on('end', function() {
                    let body = decodeParam(s.toString())
                    if (body.name === '123' && body.pwd === '456') {
                        data.data = user
                    } else {
                        data.success = false
                        data.msg = '用户名或密码错误'
                    }
                    response.writeHead(200);
                    response.end(JSON.stringify(data))
                })
            } else if (request.method === 'GET') {
                let body = request.url.split('?')[1]
                if (body) {
                    body = decodeParam(body)
                    if (body.name === '123' && body.pwd === '456') {
                        data.data = user
                    } else {
                        data.success = false
                        data.msg = '用户名或密码错误'
                    }
                    response.writeHead(200);
                    response.end(JSON.stringify(data))
                }
                console.log(request.url)
            }
        }
    }
})

server.listen(3001, () => {
    console.log('server is runing localhost:3001')
})
